package com.pan.picture.impl;

import com.pan.interfere.Interfere;
import com.pan.interfere.impl.CharInterfere;
import com.pan.picture.Picture;
import com.pan.utils.RandomColor;
import com.pan.utils.RandomFont;

import java.awt.*;
import java.awt.image.BufferedImage;

public class CharPicture implements Picture {

    private char c;
    private int fontSize;
    private BufferedImage bufferedImage;

    private Graphics2D graphics;
    private Interfere interfere;

    public CharPicture(char c) {
        this(c,48);
    }

    public CharPicture(char c, int fontSize) {
        this.c = c;
        this.fontSize = fontSize;
    }

    @Override
    public void createImage(){
        int width = fontSize + 8;
        if (bufferedImage == null || graphics ==null||interfere == null){
            this.bufferedImage = new BufferedImage(width,width,BufferedImage.TYPE_INT_RGB);
            graphics = bufferedImage.createGraphics();
            interfere = new CharInterfere(this.bufferedImage);
        }
        graphics.setBackground(RandomColor.getBackgroundColor());
        graphics.clearRect(0,0,width,width);
        graphics.setFont(RandomFont.randomAnyFont(fontSize));
        graphics.setColor(RandomColor.getR6Color());
        graphics.shear(Math.random()*0.5,0.1);
        graphics.drawString(String.valueOf(c), (int) (Math.random()*4),width-10-(int) (Math.random()*8));
    }

    @Override
    public BufferedImage getImage() {
        if (bufferedImage == null){
            createImage();
        }
        return bufferedImage;
    }


    @Override
    public void reset(String str){
        createImage();
        if (str.length()!=1) {
            throw new RuntimeException("只能传1个字符");
        }
        c = str.charAt(0);
    }

    @Override
    public void close() {
        graphics.dispose();
        interfere.close();
    }


    @Override
    public void interfere() {
        if (bufferedImage == null){
            createImage();
        }
        interfere.drawInterfere();
    }
}
